import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../services/file_service.dart';
import 'preview_utils.dart';

/// 通用文件预览组件
/// 用于显示不支持直接预览的文件类型
class GenericPreview extends StatelessWidget {
  final String? previewUrl;
  final String? fileName;
  final String? fileType;
  final String? extension;
  final String? mimeType;
  final int? fileSize;
  final VoidCallback? onRetry;

  const GenericPreview({
    Key? key,
    required this.previewUrl,
    required this.fileName,
    this.fileType,
    this.extension,
    this.mimeType,
    this.fileSize,
    this.onRetry,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // 文件图标卡片
          Card(
            elevation: 4,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(16),
            ),
            color: Colors.white,
            child: Container(
              padding: const EdgeInsets.all(30),
              width: 160,
              height: 160,
              child: Icon(
                PreviewUtils.getFileIcon(fileType, extension),
                size: 80,
                color: PreviewUtils.getFileColor(fileType),
              ),
            ),
          ),
          const SizedBox(height: 24),

          // 文件名
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 32),
            child: Text(
              fileName ?? '未知文件',
              style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              textAlign: TextAlign.center,
            ),
          ),
          const SizedBox(height: 8),

          // 文件类型和大小
          Text(
            '${mimeType ?? "文件"} · ${fileSize != null ? FileService.formatFileSize(fileSize!) : "未知大小"}',
            style: const TextStyle(color: Colors.grey),
          ),
          const SizedBox(height: 36),

          // 下载按钮
          ElevatedButton.icon(
            onPressed: () async {
              if (previewUrl != null) {
                final url = Uri.parse(previewUrl!);
                if (await canLaunchUrl(url)) {
                  await launchUrl(url, mode: LaunchMode.externalApplication);
                }
              }
            },
            icon: const Icon(Icons.download),
            label: const Text('下载文件'),
            style: ElevatedButton.styleFrom(
              backgroundColor: Theme.of(context).primaryColor,
              foregroundColor: Colors.white,
              padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 12),
            ),
          ),
        ],
      ),
    );
  }
}
